<template>
  <basic-dialog :visible="show"
                maxWidth="300px"
                minWidth="300px"
                :isShowInnerLoading = 'isShowInnerLoading'
                :title="`${titleText}${typeText}记录`">
    <q-form @submit="submit"
            greedy
            @reset="reset"
            ref="myForm"
            class="dialog-content form-inline block">
      <div class="row padding-t-20">
        <div class="col"
             v-if="type === 'partscause'">
          <q-select
                    v-model="form.gidName"
                    :options="typeOption"
                    @input="getPartscauseItem(form.gidName, true)"
                    dense
                    options-dense
                    emit-value
                    map-options
                    outlined
                    :rules="[ val => val !== '' || `请选择${typeText}类型`]">
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
          <template v-slot:before>
            <label class="text-right name label-width">
              <span class="text-red">*</span>
              <span>{{typeText}}类型:</span>
            </label>
          </template>
          </q-select>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <q-select
                    v-model="form.causeId"
                    :options="causeOptions"
                    dense
                    options-dense
                    emit-value
                    map-options
                    outlined
                    :rules="[ val => val !== '' || `请选择${typeText}原因`]">
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
          <template v-slot:before>
            <label class="text-right name label-width">
              <span class="text-red">*</span>
              <span>{{typeText}}原因:</span>
            </label>
          </template>
          </q-select>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <q-input
                   v-model.number="form.count"
                   dense
                   options-dense
                   emit-value
                   :rules="[
                     val => val !== '' || `请填写${typeText}数量`,
                     val => val > 0 || `请输入正整数`,
                     val => val <= checkCount || '不良数需≤待质检数'
                     ]"
                   map-options
                   placeholder="请输入数量"
                   outlined>
            <template v-slot:before>
              <label class="text-right name label-width">
                <span class="text-red">*</span>
                <span>{{typeText}}数量:</span>
              </label>
            </template>
          </q-input>
        </div>
      </div>
      <q-input outlined
               v-model="form.remark"
               type="textarea"
               counter
               autogrow
               maxlength="50"
               class="textarea"
               placeholder="请输入说明"
      >
        <template v-slot:before>
          <label class="text-right name">不良说明:</label>
        </template>
        <template v-slot:append>
          <q-icon
            name="iconfont icontubiao2-93"
            color="primary"
            class="cursor-pointer font-18"
            @click="onShowSymbol"
          />
        </template>
      </q-input>
      <q-input outlined
               v-if="type === 'partscause'"
               v-model="form.improveStrategy"
               type="textarea"
               counter
               autogrow
               maxlength="50"
               class="textarea"
               placeholder="请输入说明"
      >
        <template v-slot:before>
          <label class="text-right name">改善对策:</label>
        </template>
      </q-input>
      <q-separator style="margin: 0 -20px;width: calc(100% + 40px)" />
      <div class="dialog-footer text-center margin-t-10">
        <q-btn outline
               label="取消"
               color="primary"
               @click="show = false"
               class="q-mr-md"
               type="reset" />
        <q-btn unelevated
               label="确认"
               color="primary"
               type="submit" />
      </div>
    </q-form>
    <add-symbol-dialog :show="isShowSymbol" @close="isShowSymbol = false" @onSetItem="onSetItem" />
  </basic-dialog>
</template>

<script>
import { getCauseTypeList, getCauseItem } from 'src/boot/system/reason'
import {
  addQualitySubCauses,
  editQualitySubCauses
} from 'src/boot/job/quality-order'
import _ from 'lodash'
import addSymbolDialog from './add-symbol-dialog'
export default {
  name: 'bad-editor-dialog',
  computed: {
    titleText () {
      return this.isAdd ? '添加' : '编辑'
    },
    typeText () {
      return this.type === 'partscause' ? '不良' : '让步'
    }
  },
  components: {
    addSymbolDialog
  },
  data () {
    return {
      isShowSymbol: false,
      isShowInnerLoading: false,
      checkCount: 0, // 可填报数量
      isAdd: false,
      show: false,
      type: '',
      typeOption: [], // 原因类型
      // classOptions: [], // 班次
      causeOptions: [], // 原因
      recordData: {}, // 质检总
      subData: {}, // 子质检单
      form: {
        gidName: '',
        shiftsName: '',
        causeId: '',
        count: '',
        remark: '',
        label: '',
        id: '',
        deviceId: '',
        improveStrategy: ''
      }
    }
  },
  methods: {
    showDialog (recordData, type, isAdd, subData, data) {
      this.isAdd = isAdd
      this.type = type
      this.onClearForm()
      this.show = true
      this.isShowInnerLoading = true
      this.subData = subData
      // 可修改数量为，质检数量-不良数
      this.checkCount = this.subData.qualityCount - this.subData.defectiveCount - this.subData.compromiseCount
      if (isAdd) {
        type === 'partscause' ? this.getPartscauseList(true) : this.getCauseList()
      } else {
        this.checkCount = this.checkCount + data.count
        this.setFormData(data)
      }
      this.recordData = recordData
    },
    setFormData (data) {
      // this.$nextTick(() => {
      this.form.count = data.count
      this.form.remark = data.remark
      this.form.causeId = data.causeId
      this.form.id = data.id
      this.form.gidName = data.gid
      this.form.label = data.causeName
      this.form.improveStrategy = data.improveStrategy
      // this.form.deviceId = this.recordData.deviceId
      this.type === 'partscause' ? this.getPartscauseList(false) : this.getConcessioncauseList(data.gid)
      // })
    },
    // 添加
    addQualityCauses (params) {
      // const data = {
      //   vos: [params]
      // }
      addQualitySubCauses([params], this.recordData.id, this.subData.id, true).then(res => {
        if (res.code === '1200') {
          this.$message.success('添加成功')
          this.show = false
          this.$emit('getList')
        }
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    // 编辑
    editQualityCauses (params) {
      editQualitySubCauses(params, this.form.id).then(res => {
        if (res.code === '1200') {
          this.$message.success('编辑成功')
          this.show = false
          this.$emit('getList')
        }
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    // 获取原因类型
    getCauseList () {
      getCauseTypeList(2).then(res => {
        if (res.data.length > 0) {
          this.getConcessioncauseList(res.data[0].id)
        }
      })
    },
    // 获取让步原因列表
    getConcessioncauseList (typeId) {
      const params = {
        showDisable: false,
        causeGroupId: typeId
      }
      getCauseItem(params).then(res => {
        const causeOptions = []
        if (res.data.length) {
          res.data.forEach(o => {
            causeOptions.push({
              value: o.id + '',
              label: o.label
            })
          })
          if (this.isAdd) {
            this.form.causeId = causeOptions[0].value
          } else {
            !causeOptions.filter(item => this.form.causeId === item.value).length && (this.form.causeId = '')
          }
        } else {
          this.form.causeId = ''
        }
        this.causeOptions = causeOptions
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    // 获取不良原因类型列表
    getPartscauseList (init = false) {
      getCauseTypeList(1).then(res => {
        const typeOption = []
        if (res.data.length) {
          res.data.forEach(o => {
            typeOption.push({
              value: o.id + '',
              label: o.label
            })
          })
          if (this.isAdd) {
            this.form.gidName = typeOption[0].value
            this.getPartscauseItem(this.form.gidName, init)
          } else {
            if (!typeOption.filter(item => this.form.gidName === item.value).length) {
              this.form.gidName = ''
              this.form.causeId = ''
              this.isShowInnerLoading = false
            } else {
              this.getPartscauseItem(this.form.gidName, init)
            }
          }
        } else {
          this.isShowInnerLoading = false
          this.form.gidName = ''
        }
        this.typeOption = typeOption
      })
    },
    // 根据零件不良原因类型代码查询零件不良原因
    getPartscauseItem (typeId, init = false) {
      // this.form.causeId = ''
      const params = {
        id: typeId,
        showDisable: false
      }
      getCauseItem(params).then(res => {
        const causeOptions = []
        if (res.data.length) {
          res.data.forEach(o => {
            causeOptions.push({
              value: o.id + '',
              label: o.label
            })
          })
          if (this.isAdd) {
            this.form.causeId = causeOptions[0].value
          } else {
            if (init) {
              this.form.causeId = causeOptions[0].value
            } else {
              !causeOptions.filter(item => this.form.causeId === item.value).length && (this.form.causeId = '')
            }
          }
        } else {
          this.form.causeId = ''
        }
        this.causeOptions = causeOptions
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    // 提交表单
    submit () {
      this.isShowInnerLoading = true
      let params = {
        causeId: this.form.causeId,
        count: this.form.count,
        workshopId: this.recordData.workshopId,
        causeName: this.causeOptions.find(v => v.value === this.form.causeId).label,
        remark: this.form.remark,
        improveStrategy: this.form.improveStrategy
      }
      this.type === 'partscause' && (params['gid'] = this.form.gidName)
      params['inputType'] = this.type === 'partscause' ? '1' : '2'
      this.isAdd ? this.addQualityCauses(params) : this.editQualityCauses(params)
    },
    reset () {
      this.$refs.myForm.resetValidation()
    },
    // 重置form表单
    onClearForm () {
      Object.keys(this.form).forEach(v => {
        this.form[v] = ''
      })
    },
    // 选择符号
    onShowSymbol () {
      this.isShowSymbol = true
    },
    onSetItem (val) {
      if (this.form.remark.length < 50) {
        this.form.remark = `${this.form.remark}${val}`
      }
    },
    /**
     *
     *判断是否为null
     */
    isNull (val) {
      return _.isEmpty(val)
    }
  }
}
</script>

<style scoped lang="stylus">
  .q-gutter-x-md .q-gutter-md{
    margin-left 0px !important
  }

  >>>.textarea{
    .q-field__control{
      align-items flex-end
    }
  }
</style>
